package com.xinqi.printByThreadsWithLoop.byReentrantLockForever.august2_02;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xin麒
 * @date 2023/8/2 15:46
 */
public class XinThread {
    static int count = 1;

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition oddWaitSet = lock.newCondition();
        Condition evenWaitSet = lock.newCondition();
        new Thread(()->{
            while (true){
                lock.lock();
                try {
                    oddWaitSet.await(1, TimeUnit.SECONDS);
                    Thread.sleep(1000);
                    System.out.print(count++);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    evenWaitSet.signal();
                    lock.unlock();
                }
            }
        },"t1").start();

        new Thread(()->{
            while (true){
                lock.lock();
                try {
                    evenWaitSet.await();
                    Thread.sleep(1000);
                    System.out.print(count++);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    oddWaitSet.signal();
                    lock.unlock();
                }
            }
        },"t2").start();


    }
}
